//
//  HYHomeFileItemViewModel.m
//  XPlayer
//
//  Created by liguoqing on 2023/9/4.
//

#import "HYHomeFileItemViewModel.h"
#import "HYHomeFolderModel.h"
#import "HYHomeVideoModel.h"
#import "HYPreviewHistoryModel.h"
#import "HYPreviewHistoryManager.h"
#import "HYFileDownloadModel.h"
#import "HYMyCollectionModel.h"

@implementation HYHomeFileItemViewModel

/// folderModel转fileModel
- (instancetype)initWitFolderModel:(HYHomeFolderModel *)folderModel
{
    self = [super init];
    if(self){
        self.folderModel = folderModel;
        self.fileType = (HYHomeFileType)folderModel.folderType;
        self.folderLocation = folderModel.folderLocation;
        self.folderIdentification = folderModel.folderIdentification;
        self.fileName = folderModel.folderName;
//        self.filePath = [HYFileManager fetchFolderPathWithFolderName:folderModel.folderName];
        self.fileCount = folderModel.fileCount;
        self.createDate = folderModel.createDate;
        self.isLock = folderModel.isLock;
    }
    return self;
}

/// videoModel转fileModel
- (instancetype)initWitVideoModel:(HYHomeVideoModel *)videoModel
{
    self = [super init];
    if(self){
        self.videoModel = videoModel;
        self.fileType = videoModel.isAudio?HYHomeFileType_Audio:HYHomeFileType_Video;
        self.folderIdentification = videoModel.folderIdentification;
        self.fileName = videoModel.videoTitle;
        NSString *videoType = [videoModel.videoTitle componentsSeparatedByString:@"."].lastObject;
        if(videoModel.videoUrl){
            videoType = [videoModel.videoUrl componentsSeparatedByString:@"."].lastObject;
            if(videoType.length > 4 && [videoType containsString:@"&"]){
                videoType = [videoType componentsSeparatedByString:@"&"].firstObject;
            }
        }
        self.fileSuffixName = videoType;
        if(videoModel.isLocal){// 本地视频相册导入
            self.filePath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:videoModel.videoTitle];
        }else{
            self.filePath = videoModel.videoUrl;
        }
        self.fileImage = videoModel.imageName;
        self.videoDuration = videoModel.videoDuration;
        self.createDate = videoModel.createDate;
        self.importDate = videoModel.importDate;
        self.isLock = videoModel.isLock;
    }
    return self;
}

- (instancetype)initWitHistroyModel:(HYPreviewHistoryModel *)historyModel
{
    self = [super init];
    if(self){
        self.fileType = historyModel.fileType;
        self.fileName = historyModel.fileName;
        NSString *videoType = [historyModel.filePath componentsSeparatedByString:@"."].lastObject;
        if(videoType.length > 4 && [videoType containsString:@"&"]){
            videoType = [videoType componentsSeparatedByString:@"&"].firstObject;
        }
        self.fileSuffixName = videoType;
        if([historyModel.folderIdentification isEqualToString:@"fileImport-vplayer"]){
            self.filePath = [[[HYFileManager documentDirectory] stringByAppendingPathComponent:historyModel.folderPath] stringByAppendingPathComponent:historyModel.fileName];
        }else{
            self.filePath = historyModel.filePath;
        }
        self.folderPath = historyModel.folderPath;
        self.folderIdentification = historyModel.folderIdentification;
        self.createDate = historyModel.createDate;
        self.importDate = historyModel.importDate;
        self.fileImage = historyModel.videoImagePath;
        self.videoDuration = historyModel.videoDuration;
        self.playTime = historyModel.videoPlayTime;
        self.lastTime = historyModel.updateDate;
        self.isLock = historyModel.isPrivate;
        self.isHistory = YES;
        self.isHiddenSet = YES;
    }
    return self;
}

- (instancetype)initWitCollectModel:(HYMyCollectionModel *)collectModel
{
    self = [super init];
    if(self){
        NSArray *filePaths = [collectModel.filePath componentsSeparatedByString:@"."];
        self.fileType = collectModel.fileType;
        self.fileName = collectModel.fileName;
        self.fileSuffixName = filePaths.lastObject;
        if([collectModel.folderIdentification isEqualToString:@"fileImport-vplayer"]){
            NSString *filePrefixPath = [[[HYFileManager documentDirectory] stringByAppendingPathComponent:collectModel.folderPath] stringByAppendingPathComponent:collectModel.fileName];
            self.filePath = filePrefixPath;
        }else if([collectModel.filePath containsString:@"http"] || [collectModel.filePath containsString:@"file://"]){
            self.filePath = collectModel.filePath;
        }else{
            self.filePath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:collectModel.fileName];
        }
        self.folderPath = collectModel.folderPath;
        self.folderIdentification = collectModel.folderIdentification;
        self.createDate = collectModel.createDate;
        self.videoImage = [UIImage imageNamed:[HYFileManager videoImageSavePathWithFileName:collectModel.videoImagePath]];
        self.importDate = collectModel.importDate;
        self.fileImage = collectModel.videoImagePath;
        self.videoDuration = collectModel.videoDuration;
        self.isLock = collectModel.isPrivate;
        self.isHiddenSet = YES;
    }
    return self;
}

#pragma mark - 更新文件名
- (BOOL)modifyFileNameToDB
{
    if(self.fileType != HYHomeFileType_Video && self.fileType != HYHomeFileType_Audio){
        self.folderModel.folderName = self.fileName;
        return [self.folderModel updateToDB];
    }else{
        NSString *videoTile = self.videoModel.videoTitle;
        NSString *newVideoName = self.fileName;
        if(self.videoModel.isLocal){
            // 修改沙盒视频名称
            NSString *oldVideoPath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:self.videoModel.videoTitle];
            NSString *newVideoPath = [HYFileManager moveFolderPathOldFolderPath:oldVideoPath newFolderName:newVideoName];
            if(newVideoPath.length){
                self.filePath = newVideoPath;
                // 获取所有相同的视频模型，同时修改文件名
                NSArray *videoArray = [HYHomeVideoModel searchWithSQL:[NSString stringWithFormat:@"select * from VIDEOLIST where videoTitle = '%@'",self.videoModel.videoTitle]];
                [videoArray enumerateObjectsUsingBlock:^(HYHomeVideoModel *videoModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if(![self.videoModel.folderIdentification isEqualToString:videoModel.folderIdentification]){
                        videoModel.videoTitle = newVideoName;
                        [videoModel saveToDB];
                    }
                }];
                self.videoModel.videoTitle = newVideoName;
            }
        }else{
            self.videoModel.videoTitle = newVideoName;
        }
        BOOL result = [self.videoModel updateToDB];
        if(result){
            if([self.videoModel.videoUrl containsString:@"http"]){
                [HYFileDownloadModel updateDownloadFileName:self.fileName fileUrl:self.videoModel.videoUrl];
            }
            // 修改浏览记录中视频名称
            [HYPreviewHistoryManager modifyHistoryRecordVideoTitle:videoTile videoModel:self.videoModel];
        }
        return result;
    }
}
#pragma mark - 修改沙盒下的文件名
- (BOOL)modifyFileNameToSandbox
{
    // 创建新的文件路径
    NSString *newFolderPath = [HYFileManager moveFolderPathOldFolderPath:self.filePath newFolderName:self.fileName];
    if(newFolderPath.length){
        self.filePath = newFolderPath;
        return YES;
    }
    return NO;
}

#pragma mark - 移除文件
- (BOOL)deleteFileToDB
{
    BOOL result = NO;
    if(self.fileType == HYHomeFileType_Folder){
        result = [self.folderModel deleteToDB];
        if(result){
            NSArray *videoArray = [HYHomeVideoModel searchWithSQL:[NSString stringWithFormat:@"select * from VIDEOLIST where folderIdentification = '%@'",self.folderIdentification]];
            if(videoArray.count){
                for (HYHomeVideoModel *videoModel in videoArray) {
                    NSArray *videoArray = [HYHomeVideoModel searchWithSQL:[NSString stringWithFormat:@"select * from VIDEOLIST where videoTitle = '%@'",videoModel.videoTitle]];
                    if(videoArray.count == 1){// 如果只有一条 移除沙盒中的视频和视频封面
                        // 移除视频封面
                        NSString *videoImagePath = [HYFileManager videoImageSavePathWithFileName:videoModel.imageName];
                        [kFileManager removeItemAtPath:videoImagePath error:nil];
                        // 移除本地视频
                        NSString *videoLocalPath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:videoModel.videoTitle];
                        [kFileManager removeItemAtPath:videoLocalPath error:nil];
                    }
                    [videoModel deleteToDB];
                }
                // 移除浏览记录
                [HYPreviewHistoryManager removeHistoryRecordWithFolderModel:self.folderModel];
            }
        }
        return result;
    }else if(self.fileType == HYHomeFileType_Video || self.fileType == HYHomeFileType_Audio){
        if(self.videoModel.isLocal){// 判断当前文件夹在其他文件夹是否存在
            NSArray *videoArray = [HYHomeVideoModel searchWithSQL:[NSString stringWithFormat:@"select * from VIDEOLIST where videoTitle = '%@'",self.videoModel.videoTitle]];
            if(videoArray.count == 1){// 如果只有一条 移除沙盒中的视频和视频封面
                // 移除视频封面
                NSString *videoImagePath = [HYFileManager videoImageSavePathWithFileName:self.videoModel.imageName];
                [kFileManager removeItemAtPath:videoImagePath error:nil];
                // 移除本地视频
                NSString *videoLocalPath = [HYFileManager fetchPhotoVideoImportPathWithVideoName:self.videoModel.videoTitle];
                [kFileManager removeItemAtPath:videoLocalPath error:nil];
            }
        }
        result = [self.videoModel deleteToDB];
        if(result){
            [HYPreviewHistoryManager removeHistoryRecordWithVideoModel:self.videoModel];
        }
    }
    return result;
}

- (BOOL)removeDocumentFile
{
    BOOL isRemove = [kFileManager removeItemAtPath:self.filePath error:nil];
    if(isRemove){
        // 移除浏览记录
        if(self.fileType == HYHomeFileType_Folder){
            [HYPreviewHistoryManager removeDocumentHistoryRecordWithFolderPath:[NSString stringWithFormat:@"/%@",self.fileName]
                                                          folderIdentification:self.folderIdentification];
        }else if(self.fileType == HYHomeFileType_Video || self.fileType == HYHomeFileType_Audio){
            [HYPreviewHistoryManager removeHistoryRecordWithVideoTitle:self.fileName
                                                            createDate:self.createDate];
        }
    }
    return isRemove;
}

#pragma mark - 移动文件夹
- (BOOL)moveFileLocationToDB
{
    BOOL result = NO;
    if(self.fileType == HYHomeFileType_Folder){
        NSString *folderIdentitfication = self.folderModel.folderIdentification;
        self.folderModel.folderLocation = self.folderLocation;
        result = [self.folderModel updateToDB];
        if(result){
            [HYPreviewHistoryManager updateHistoryRecordFolderIdentification:folderIdentitfication folderModel:self.folderModel];
        }
    }else if(self.fileType == HYHomeFileType_Video || self.fileType == HYHomeFileType_Audio){
        NSString *folderIdentitfication = self.videoModel.folderIdentification;
        self.videoModel.folderIdentification = self.folderIdentification;
        result = [self.videoModel updateToDB];
        if(result){
            [HYPreviewHistoryManager updateHistoryRecordFolderIdentification:folderIdentitfication videoModel:self.videoModel];
        }
    }
    return result;
}

#pragma mark - 移动文件或文件夹（沙盒下）
- (BOOL)moveDocumentFileToFolderPath:(NSString *)folderPath
{
    BOOL result = NO;
    if(self.fileType == HYHomeFileType_Folder){
        NSString *folerPath = self.folderPath.length?[self.folderPath stringByAppendingPathComponent:self.fileName]:[NSString stringWithFormat:@"/%@",self.fileName];
        NSString *newFolderPath = folderPath.length?[folderPath stringByAppendingPathComponent:self.fileName]:[NSString stringWithFormat:@"/%@",self.fileName];
        [HYPreviewHistoryManager updateHistoryRecordFolderPath:folerPath
                                          folderIdentification:self.folderIdentification
                                                 newFolderPath:newFolderPath];
    }else if(self.fileType == HYHomeFileType_Video || self.fileType == HYHomeFileType_Audio){
        [HYPreviewHistoryManager updateHistoryRecordFolderPath:self.folderPath
                                                   fileName:self.fileName
                                              newFolderPath:folderPath];
    }
    return result;
}

#pragma mark - 文件夹加锁
- (BOOL)lockOrUnLockFolderToDB
{
    if(self.fileType != HYHomeFileType_Video && self.fileType != HYHomeFileType_Audio){
        self.folderModel.isLock = self.isLock;
        BOOL result = [self.folderModel updateToDB];
        if(result){
            [HYPreviewHistoryManager setPrivateHistoryRecordWithFolderModel:self.folderModel];
        }
        return result;
    }else{
        self.videoModel.isLock = self.isLock;
        BOOL result = [self.videoModel updateToDB];
        if(result){
            [HYPreviewHistoryManager setPrivateHistoryRecordWithVideoModel:self.videoModel];
        }
        return result;
    }
}

@end
